<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-20
 * Time: 10:00
 */

namespace doumiaoduo\ueditor;


use yii\helpers\Html;
use yii\helpers\Json;
use yii\widgets\InputWidget;

class Ueditor extends InputWidget{

    public $clientOptions = [];

    public $serverParam=[];

    public function init(){
        if(isset($this->clientOptions['serverUrl'])){
            $this->clientOptions['serverUrl']=str_replace('action','',$this->clientOptions['serverUrl']);
            $this->clientOptions['serverUrl']=str_replace(urlencode('action'),'',$this->clientOptions['serverUrl']);
        }
        $this->clientOptions['csrf-param']=\Yii::$app->request->csrfParam;
        $this->clientOptions['csrf-token']=\Yii::$app->request->getCsrfToken();
        $this->name=$this->hasModel()?Html::getInputName($this->model,$this->attribute):$this->name;
        parent::init();
    }

    public function run()
    {
        $this->value=$this->hasModel()?Html::getAttributeValue($this->model,$this->attribute):$this->value;
        echo '<script id="'.$this->options['id'].'" name="'.$this->name.'" type="text/plain">'.$this->value.'</script>';
        $this->registerClientScript();
    }

    public function registerClientScript(){
        $id=str_replace('-','_',$this->options['id']);
        $view = $this->getView();
        UeditorAsset::register($view);
        $options=Json::htmlEncode($this->clientOptions);
        $js="var ue_{$id} = UE.getEditor('{$this->options['id']}',$options); \n";
        if(!empty($this->serverParam)){
            $params=Json::htmlEncode($this->serverParam);
            $js.="ue_{$id}.ready(function() {
            ue_{$id}.execCommand('serverparam', function(editor) {
                    return {$params};
                });
            }); ";
        }
        $view->registerJs($js);
    }

}